package at.fhj.itm11.fotorater.data;

import java.util.List;

import javax.faces.bean.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import at.fhj.itm11.fotorater.model.Category;
import at.fhj.itm11.fotorater.model.Photo;

@ApplicationScoped
public class CategoryRepository {

	@Inject
	private EntityManager em;

	public Category findById(Long id) {
		return em.find(Category.class, id);
	}

	/**
	 * Returns the category, which is associated to the forwarded name.
	 * Returns only one category, because the name of the category has to be
	 * unique.
	 * 
	 * @param name name of the category
	 * @return the category
	 */
	public Category findByName(String name) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Category> criteria = cb.createQuery(Category.class);
		Root<Category> category = criteria.from(Category.class);

		criteria.select(category).where(cb.equal(category.get("name"), name));
		return em.createQuery(criteria).getSingleResult();
	}
	
	@Deprecated
	public List<Photo> findPhotosForCategory(Category cat) {
		return cat.getPhotos();
	}
	
	@Deprecated
	public List<Photo> findPhotosForCategory(Long id) {
		Category cat = findById(id);
		return findPhotosForCategory(cat);
	}
	
	public List<Category> findAllOrderedByName() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Category> criteria = cb.createQuery(Category.class);
		Root<Category> category = criteria.from(Category.class);
		
		criteria.select(category).orderBy(cb.asc(category.get("name")));
		return em.createQuery(criteria).getResultList();
	}
}
